#ifndef EZQHTTP_H
#define EZQHTTP_H

#include <QObject>
#include <QNetworkReply>
#include <QNetworkRequest>
#include <QNetworkAccessManager>
#include "EZTally/EZTallyObject.h"

namespace EZQHTTPNS {

//class EZQHttpIO
//{
//public:
//    virtual void httpWrite(QByteArray &bytearray);
//};

typedef enum{
    HttpStatus_init,
    HttpStatus_start,
    HttpStatus_runing,
    HttpStatus_finish,
    HttpStatus_error,
    HttpStatus_cancel
}HttpStatus;

class EZQHttp : public QObject ,public EZTally::EZTallyObject
{
    Q_OBJECT
public:
    explicit EZQHttp();
protected:
    virtual ~EZQHttp();

public:

    QString url() const;
    void setUrl(const QString &url);

    void reset();

    virtual void startAsync();
    void startSync();

    QString method() const;
    void setMethod(const QString &method);

    void setHeader(const QString &key,const QString &value);
    void setHeader(QNetworkRequest::KnownHeaders type,QString value);
    void addPostValue(const QString &key,const QString &value);
    QByteArray responseBytes();
    qint64 readBytes(char *buf,const qint64 &offset,const qint64 &bufLen);

    void setNeedProgress(bool isNeed);
    bool isNeedProgress() const;

    QString downLoadPath() const;
    void setDownLoadPath(const QString &downLoadPath);

    qint64 receiveByteLen();

    HttpStatus status();

    qint64 respondTotalSize() const;
    void setRespondTotalSize(const qint64 &respondTotalSize);

    int responseCode() const;
protected:
    void startRequest();

signals:
    void statusChange(EZQHTTPNS::HttpStatus);
    void finish();
    void downloadProgress(qint64,qint64);
public slots:
    void cancel();
protected slots:
    void psl_httpFinish(QNetworkReply*);
    void psl_downloadProgress(qint64,qint64);
protected :
    void saveToPath();
protected:

    QMutex _mutex;

    QString _url;
    QString _method;


    QNetworkRequest *_request;
    QNetworkReply *_reply;

    QNetworkAccessManager *_accessmanager;

    QByteArray _postByte;

    bool _isNeedProgress;
    QByteArray _receiveByte;
    qint64 _receiveByteLen;
    qint64 _respondTotalSize;
    void setReceiveByteLen(const qint64 &receiveByteLen);

    int _responseCode;
    void setResponseCode(int responseCode);

    QString _downLoadPath;
    qint64 _cacheReciveByteLen;

    HttpStatus _status;
    void setStatus(const HttpStatus &status);
};


}



#endif // EZQHTTP_H
